/*
 * Copyright (C) 2009 Jiannan Lu
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.restsql.xmlconfig;

/**
 *`@Reference http://www.ibm.com/developerworks/xml/library/x-jschema/#XMLConfigurator
 * @author L
 */
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;

import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.net.URL;

//使用DefaultHandler的好处 是 不必陈列出所有方法,
public class XMLConfigurator extends DefaultHandler {

////定义一个Properties 用来存放 dbhost dbuser dbpassword的值
    private Properties props;
    private String currentSet;
    private String currentName;
    private StringBuffer currentValue = new StringBuffer();

    public XMLConfigurator() {

        this.props = new Properties();
    }

    public Properties getProps() {
        return this.props;
    }

    public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException {
        currentValue.delete(0, currentValue.length());
        this.currentName = qName;

    }

    public void characters(char[] ch, int start, int length) throws SAXException {

        currentValue.append(ch, start, length);

    }

    public void endElement(String uri, String localName, String qName) throws SAXException {

        props.put(qName, currentValue.toString().trim());
    }

    public void parse(String filename) throws Exception {

        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);


        SAXParser parser = factory.newSAXParser();


        try {
            parser.parse(filename, this);
        } finally {
            factory = null;
            parser = null;
        }

    }
}



